#!/usr/bin/env python3
import cv2, os, sys
from datetime import datetime

# 接收命令行参数：保存目录
pic_dir = sys.argv[1] if len(sys.argv) > 1 else os.path.expanduser("~/Pictures")
os.makedirs(pic_dir, exist_ok=True)

# 打开摄像头
cap = cv2.VideoCapture(0, cv2.CAP_V4L2)
if not cap.isOpened():
    print("❌ 无法打开摄像头，请检查连接")
    sys.exit(1)

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

while True:
    ret, frame = cap.read()
    if not ret:
        print("❌ 无法读取画面")
        break

    cv2.imshow("Microscope Live", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord('s'):
        filename = f"microscope_{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
        filepath = os.path.join(pic_dir, filename)
        cv2.imwrite(filepath, frame)
        print(f"✅ 已保存：{filepath}")
    elif key == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()